<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 聊天助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            background-color: #f5f5f5;
            color: #333;
        }

        .chat-container {
            max-width: 800px;
            margin: 20px auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            height: 90vh;
        }

        .chat-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            text-align: center;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            margin: 0 12px;
        }

        .user .message-content {
            background-color: #007AFF;
            color: white;
        }

        .assistant .message-content {
            background-color: #f0f0f0;
            color: #333;
        }

        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        .user .avatar {
            background-color: #007AFF;
            color: white;
        }

        .chat-input {
            padding: 20px;
            border-top: 1px solid #eee;
            display: flex;
            gap: 10px;
        }

        .chat-input textarea {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            resize: none;
            height: 50px;
            font-family: inherit;
            font-size: 14px;
        }

        .chat-input button {
            padding: 0 24px;
            background-color: #007AFF;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .chat-input button:hover {
            background-color: #0056b3;
        }

        .chat-input button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h2>AI 聊天助手</h2>
        </div>
        <div class="chat-messages" id="messageContainer"></div>
        <div class="chat-input">
            <textarea id="userInput" placeholder="请输入您的问题..."></textarea>
            <button id="sendButton">发送</button>
        </div>
    </div>
    <script>
        const messageContainer = document.getElementById('messageContainer');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');

        function addMessage(content, isUser = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user' : 'assistant'}`;

            const avatar = document.createElement('div');
            avatar.className = 'avatar';
            avatar.textContent = isUser ? 'U' : 'A';

            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageContent.textContent = content;

            messageDiv.appendChild(avatar);
            messageDiv.appendChild(messageContent);
            messageContainer.appendChild(messageDiv);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }

        function sendMessage() {
            const question = userInput.value.trim();
            if (!question) return;

            // 禁用输入和按钮
            userInput.disabled = true;
            sendButton.disabled = true;

            // 显示用户消息
            addMessage(question, true);

            // 清空输入框
            userInput.value = '';

            // 创建一个新的消息元素用于显示AI的回复
            const aiMessageDiv = document.createElement('div');
            aiMessageDiv.className = 'message assistant';
            const aiAvatar = document.createElement('div');
            aiAvatar.className = 'avatar';
            aiAvatar.textContent = 'A';
            const aiContent = document.createElement('div');
            aiContent.className = 'message-content';
            aiMessageDiv.appendChild(aiAvatar);
            aiMessageDiv.appendChild(aiContent);
            messageContainer.appendChild(aiMessageDiv);

            // 发送请求到后端API
            fetch('/api/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ question: question })
            }).then(response => {
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                function processText(text) {
                    const lines = text.split('\n');
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') {
                                // 启用输入和按钮
                                userInput.disabled = false;
                                sendButton.disabled = false;
                                userInput.focus();
                                return;
                            }
                            aiContent.textContent += data;
                            messageContainer.scrollTop = messageContainer.scrollHeight;
                        }
                    }
                }

                function readStream() {
                    return reader.read().then(({done, value}) => {
                        if (done) {
                            if (buffer) {
                                processText(buffer);
                            }
                            return;
                        }

                        buffer += decoder.decode(value, {stream: true});
                        const lines = buffer.split('\n\n');
                        buffer = lines.pop();
                        for (const line of lines) {
                            processText(line);
                        }

                        return readStream();
                    });
                }

                return readStream();
            }).catch(error => {
                console.error('Error:', error);
                aiContent.textContent = '抱歉，发生了错误，请重试。';
                // 启用输入和按钮
                userInput.disabled = false;
                sendButton.disabled = false;
                userInput.focus();
            });
        }

        sendButton.addEventListener('click', sendMessage);

        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>